//
//  JMPersonMessViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/8/31.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMPersonMessViewController.h"
#import "JMPersonCell.h"
#import "JMModifyPerMessViewController.h"

#import "JMSeletedTimeSheet.h"
#import "JMSeletedSexSheet.h"
#import "JMSeletedGradeSheet.h"
#import "JMSeletedLiberalArtsSheet.h"
#import "JMSeletedCitySheet.h"



#import "JMAppNetworkClient.h"
#import <UIButton+WebCache.h>
#import "JMLoginViewController.h"





@interface JMPersonMessViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,JMSeletedSexSheeDelegate,JMSeletedTimeSheeDelegate,JMSeletedGradeSheeDelegate,JMSeletedLiberalArtsSheeDelegate,JMSeletedCitySheeDelegate>{
    UIButton *currIconButton;
    
    NSIndexPath *seletedIndex;
}


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *downDataArray;

@property (nonatomic, strong) JMSeletedSexSheet * seletedSexSheet;

@property (nonatomic, strong) JMSeletedTimeSheet *seletedTimeSheet;

@property (nonatomic, strong) JMSeletedGradeSheet * seletedGradeSheet;

@property (nonatomic, strong) JMSeletedLiberalArtsSheet *seletedLiberalrtsSheet;

@property (nonatomic, strong) JMSeletedCitySheet *seletedCitySheet;




@end

@implementation JMPersonMessViewController


- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        tableView.frame = self.view.bounds;
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
        [_dataArray addObjectsFromArray:@[@[@"昵称",@"性别",@"出生日期",@"省份证号码"],
                                          @[@"高中学校",@"高中年级",@"文理科"],
                                          @[@"微信号",@"qq号",@"邮箱"],
                                          @[@"所在城市"]]];
    }
    return _dataArray;
}
- (NSMutableArray *)downDataArray
{
    if (!_downDataArray) {
        _downDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _downDataArray;
}

- (JMSeletedSexSheet *)seletedSexSheet
{
    if (!_seletedSexSheet) {
        _seletedSexSheet = [[JMSeletedSexSheet alloc]initWithLeftTitle:@"取消" rightTitle:@"确定"];
        _seletedSexSheet.delegate= self;
    }
    return _seletedSexSheet;
}

- (JMSeletedTimeSheet *)seletedTimeSheet
{
    if (!_seletedTimeSheet) {
        _seletedTimeSheet = [[JMSeletedTimeSheet alloc]initWithLeftTitle:@"取消" rightTitle:@"确定"];
        _seletedTimeSheet.delegate= self;
    }
    return _seletedTimeSheet;
}
- (JMSeletedGradeSheet *)seletedGradeSheet
{
    if (!_seletedGradeSheet) {
        _seletedGradeSheet = [[JMSeletedGradeSheet alloc]initWithLeftTitle:@"取消" rightTitle:@"确定"];;
        _seletedGradeSheet.delegate=self;
    }
    return _seletedGradeSheet;
}

- (JMSeletedLiberalArtsSheet *)seletedLiberalrtsSheet
{
    if (!_seletedLiberalrtsSheet) {
        _seletedLiberalrtsSheet = [[JMSeletedLiberalArtsSheet alloc]initWithLeftTitle:@"取消" rightTitle:@"确定"];
        _seletedLiberalrtsSheet.delegate=self;
    }
    return _seletedLiberalrtsSheet;
}


- (JMSeletedCitySheet *)seletedCitySheet
{
    if (!_seletedCitySheet) {
        _seletedCitySheet = [[JMSeletedCitySheet alloc]initWithLeftTitle:@"取消" rightTitle:@"确定"];
        _seletedCitySheet.delegate=self;
    }
    return _seletedCitySheet;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"我的志愿星";
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [JMAppNetworkClient getUserInfoWithInfo:dict complete:^(id data, NSError *error) {
            [JMTools hiddenAlerView:self.view];

            if([data[@"status"] integerValue] == 1){
                
                [JMTools showAlertView:self.view message:data[@"message"]];
                [self.downDataArray removeAllObjects];
                [self.downDataArray addObject:@[data[@"pic"]]];
                [self.downDataArray addObject:@[data[@"login"],//0:未选,1:男,-1:女）
                                                [NSString stringWithFormat:@"%@",data[@"sex"]],
                                                data[@"birthday"]]];
                [self.downDataArray addObject:@[data[@"mschool"],
                                                data[@"grade"],
                                                data[@"wenli"]]];
                [self.downDataArray addObject:@[data[@"im"],
                                                data[@"qqnumber"],
                                                data[@"email"]]];
                
                [self.downDataArray addObject:@[data[@"city"]]];
                [self.tableView reloadData];
            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
            }
            
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
}
#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 3;
    }else if (section == 2){
        return 3;
    }else if (section == 3){
        return 3;
    }else{
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        static NSString * str=@"IDIMage";
        JMPersonCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMPersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            cell.selected =NO;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        currIconButton = cell.iconImageView;
        [cell.iconImageView addTarget:self action:@selector(seletedIconImage:) forControlEvents:UIControlEventTouchUpInside];
        cell.iconImageView.backgroundColor = [UIColor clearColor];
        if(self.downDataArray.count > 0){
        [cell.iconImageView sd_setBackgroundImageWithURL:[NSURL URLWithString:self.downDataArray[indexPath.section][indexPath.row]] forState:UIControlStateNormal];
        }
        return cell;
    }else{
        static NSString * str=@"ID";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = [[self.dataArray objectAtIndex:indexPath.section - 1] objectAtIndex:indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:UI_SCREEN_WITH *0.0375];
        if(self.downDataArray.count >0){
            if(indexPath.section == 1 && indexPath.row == 1){
                int  i = (int)[self.downDataArray[indexPath.section][indexPath.row] integerValue];
                if( i==0){
                    cell.detailTextLabel.text = @"为选择";
                }else if(i == 1){
                    cell.detailTextLabel.text = @"男";
                }else{
                    cell.detailTextLabel.text = @"女";
                }
            }else if(indexPath.section == 2 && indexPath.row ==1){
                
                cell.detailTextLabel.text = self.downDataArray[indexPath.section][indexPath.row];
               
            }else if(indexPath.section == 2 && indexPath.row ==2){
                int  i = (int)[self.downDataArray[indexPath.section][indexPath.row] integerValue];
                if( i==0){
                    cell.detailTextLabel.text = @"为选择";
                }else if(i == 1){
                    cell.detailTextLabel.text = @"文科";
                }else{
                    cell.detailTextLabel.text = @"理科";
                }
            }else{
              cell.detailTextLabel.text = self.downDataArray[indexPath.section][indexPath.row];
            }
            cell.detailTextLabel.font = [UIFont systemFontOfSize:UI_SCREEN_WITH *0.0365];
            cell.detailTextLabel.textColor = UIColorFromRGB(0xc4c4c4);
        }
        return cell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    seletedIndex = indexPath;
    if(indexPath.section == 1 && indexPath.row == 1){
        [self.seletedSexSheet showInView:self.view];
    }else if(indexPath.section == 1 && indexPath.row == 2){
        [self.seletedTimeSheet showInView:self.view];
    }else if(indexPath.section == 2 && indexPath.row == 1){
        [self.seletedGradeSheet showInView:self.view];
    }else if(indexPath.section == 2 && indexPath.row == 2){
        [self.seletedLiberalrtsSheet showInView:self.view];
    }else if(indexPath.section == 4 && indexPath.row == 0){
        [self.seletedCitySheet showInView:self.view];
    }else{
        JMModifyPerMessViewController *vc = [JMModifyPerMessViewController new];
        if(indexPath.section == 1 && indexPath.row == 0){
            vc.type = ModifyPersonMessageName;
        }else if(indexPath.section == 2 && indexPath.row == 0){
            vc.type = ModifyPersonMessageSchool;
        }else if(indexPath.section == 3 && indexPath.row == 0){
            vc.type = ModifyPersonMessageWeiXin;
        }else if(indexPath.section == 3 && indexPath.row == 1){
            vc.type = ModifyPersonMessageQQ;
        }else if(indexPath.section == 3 && indexPath.row == 2){
            vc.type = ModifyPersonMessageEmail;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section ==0){
        return UI_SCREEN_WITH *0.1875;
    }else{
        return UI_SCREEN_WITH *0.109475;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return UI_SCREEN_HEIGHT *0.026408;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

#pragma mark   xuan zhe tou xiang zhao pian

-(void)seletedIconImage:(id)sender{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"关闭" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"照相机",nil];//关闭按钮在最后
    sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;//样式
    [sheet showInView:self.view];//显示样式

}
#pragma mark - action sheet delegte
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0: //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 1: //相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage  * image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dict setObject:cf.deviceString forKeyedSubscript:@"device"];
    [dict setObject:cf.signString forKeyedSubscript:@"sign"];
    [dict setObject:cf.projectID forKeyedSubscript:@"appid"];
    if(cf.user){
        [dict setObject:cf.user.userId forKeyedSubscript:@"user"];
        [dict setObject:cf.user.token forKeyedSubscript:@"token"];
        [JMTools postImageRequestAFNetWorkingDict:dict imageArray:@[image] type:@"1" block:^(id data, NSError *error) {
            [currIconButton setImage:image forState:UIControlStateNormal];
            NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];
            JMUser *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            user.picString = data[@"pic"];
            [NSKeyedArchiver archiveRootObject:user toFile:path];
            
        }];
    }
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark  delegate  fang fa 
-(void)seletedCompletSexButton:(NSString *)dataString{
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
    if([dataString isEqualToString:@"男"]){
        dataString = @"1";
    }else if([dataString isEqualToString:@"女"]){
        dataString = @"-1";
    }
    [dict setObject:dataString forKey:@"sex"];
    [self personMessModify:dict];
}
-(void)seletedCompletButton:(NSString *)dataString{
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
        [dict setObject:dataString forKey:@"birthday"];
    [self personMessModify:dict];
}
-(void)seletedCompletGradeButton:(NSString *)dataString{
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dict setObject:dataString forKey:@"grade"];
    [self personMessModify:dict];
}
-(void)seletedCompletLiberalArtsButton:(NSString *)dataString{
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
    if([dataString isEqualToString:@"文科"]){
        dataString = @"1";
    }else if([dataString isEqualToString:@"理科"]){
        dataString = @"2";
    }
    [dict setObject:dataString forKey:@"wenli"];
    [self personMessModify:dict];
}
-(void)seletedCompletCityButton:(NSString *)dataString city:(NSString *)dataString2{
    NSMutableDictionary  *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dict setObject:dataString forKey:@"province"];
    [dict setObject:dataString2 forKey:@"city"];
    [self personMessModify:dict];
}

-(void)personMessModify:(NSDictionary *)newDict{
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict addEntriesFromDictionary:newDict];
        
        [JMAppNetworkClient alterUserInfoWithInfo:dict complete:^(id data, NSError *error) {
            if([data[@"status"] integerValue] == 1){
                NSArray *keyArray = [newDict allKeys];
                if(keyArray.count == 1){
                    NSString * key = [[newDict allKeys] lastObject];
                    NSMutableArray * arr = [self.downDataArray[seletedIndex.section] mutableCopy];
                    [arr replaceObjectAtIndex:seletedIndex.row withObject:newDict[key]];
                    [self.downDataArray replaceObjectAtIndex:seletedIndex.section withObject:arr];
                }else if(keyArray.count >1){
                    NSString *str = @"";
                    for(int  i = 0; i<keyArray.count;i++){
                        str = [str stringByAppendingPathComponent:newDict[keyArray[i]]];
                    }
                    NSMutableArray * arr = [self.downDataArray[seletedIndex.section] mutableCopy];
                    [arr replaceObjectAtIndex:seletedIndex.row withObject:str];
                    [self.downDataArray replaceObjectAtIndex:seletedIndex.section withObject:arr];
                }
                [self.tableView reloadData];
                [JMTools showAlertView:self.view message:data[@"message"]];
                [self personalInformationStorage];

            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
                JMLoginViewController *vc =[JMLoginViewController new];
                JMNavigationController *nav = [[JMNavigationController alloc]initWithRootViewController:vc];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }
            [JMTools hiddenAlerView:self.view];
        }];
    }
}



- (void)personalInformationStorage{
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];
    JMUser *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    if(seletedIndex.section ==0){
    
    }else if(seletedIndex.section == 1){
        NSString *str=  self.dataArray[seletedIndex.section-1][seletedIndex.row];
        switch (seletedIndex.row) {
            case 1:{
                user.sexString = str;
            }break;
            case 2:{
                user.brithDate= str;
            }break;
            default:
                break;
        }
    
    }else if(seletedIndex.section == 2){
        NSString *str=  self.dataArray[seletedIndex.section -1][seletedIndex.row];
        if (seletedIndex.row  == 2) {
            user.wenli = str;
        }
    }else if(seletedIndex.section == 4){
        if(seletedIndex.row == 0){
            NSString *str=  self.dataArray[seletedIndex.section-1][seletedIndex.row];
            user.dizhi = str;
        }
    }
    [NSKeyedArchiver archiveRootObject:user toFile:path];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
